Node.js File System Module

Node.js

Node.js फ़ाइल सिस्टम मॉड्यूल का परिचय

Node.js File System (fs) .

यह आपको सिंक्रोनस और एसिंक्रोनस दोनों पथों में फ़ाइल I/O संचालन करने की अनुमति देता है।

ℹ️नोट:

फ़ाइल सिस्टम मॉड्यूल Node.js का एक महत्वपूर्ण मॉड्यूल है, इसलिए किसी इंस्टॉलेशन की आवश्यकता नहीं है।

फ़ाइल संचालन

फ़ाइलें आगे बढ़ाना और लिखना

निर्देशिका कार्य

निर्देशिकाएँ बनाना और हटाना

उन्नत विशेषताएँ

फ़ाइल स्ट्रीम, फ़ाइल ट्रैकिंग

फ़ाइल सिस्टम मॉड्यूल आयात करना

आप CommonJS require() या ES मॉड्यूल आयात सिंटैक्स का उपयोग करके फ़ाइल सिस्टम मॉड्यूल आयात कर सकते हैं:

CommonJS (Node.js में डिफ़ॉल्ट)

const fs = require('fs');

ES Modules (Node.js 14+ with "type": "module" in package.json)

import fs from 'fs';
// Or for specific methods:
// import { readFile, writeFile } from 'fs/promises';

वादा-आधारित एपीआई

Node.js fs/promises File System API promise- , :

// Using promises (Node.js 10.0.0+)
const fs = require('fs').promises;

// Or with destructuring
const { readFile, writeFile } = require('fs').promises;

// Or with ES modules
// import { readFile, writeFile } from 'fs/promises';

सामान्य उपयोग के मामले

फ़ाइल संचालन

  • फ़ाइलें आगे बढ़ाना और लिखना
  • फ़ाइलें बनाना और हटाना
  • फ़ाइलें जोड़ना
  • फ़ाइलों का नाम बदलना और स्थानांतरित करना
  • फ़ाइल अनुमतियाँ बदलना

निर्देशिका कार्य

  • निर्देशिकाएँ बनाना और हटाना
  • निर्देशिका सामग्री सूचीबद्ध करना
  • ट्रैकिंग फ़ाइल परिवर्तन
  • फ़ाइल/निर्देशिका आँकड़े प्राप्त करना
  • फ़ाइल उपलब्धता की जाँच की जा रही है

उन्नत विशेषताएँ

  • फ़ाइल स्ट्रीम
  • फ़ाइल विवरणकर्ता
  • छोटे लिंक
  • फ़ाइल ट्रैकिंग
  • फ़ाइल अनुमतियों के साथ कार्य करना

प्रदर्शन युक्ति:

बड़ी फ़ाइलों के लिए, उच्च मेमोरी उपयोग से बचने के लिए स्ट्रीम (fs.createReadStream और fs.createWriteStream) का उपयोग करें।

फ़ाइलें ले जाना

Node.js , callback- promise- .

सबसे आम तरीका fs.readFile() है।

⚠️नोट:

फ़ाइल संचालन के साथ काम करते समय हमेशा त्रुटियों को संभालें, जो आपके एप्लिकेशन को क्रैश होने से बचाएगा।

कॉलबैक के साथ स्टेपिंग फ़ाइलें

पारंपरिक कॉलबैक विधि का उपयोग करके फ़ाइल को चरणबद्ध करने का तरीका यहां बताया गया है:

myfile.txt

This is the content of myfile.txt

उदाहरण: कॉलबैक के साथ फ़ाइल प्रोसेसिंग

const fs = require('fs');

// Read file asynchronously with callback
fs.readFile('myfile.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log('File content:', data);
});

// For binary data (like images), omit the encoding
fs.readFile('image.png', (err, data) => {
  if (err) throw err;
  // data is a Buffer containing the file content
  console.log('Image size:', data.length, 'bytes');
});

वादों के साथ फ़ाइलें स्थानांतरित करना (उन्नत दृष्टिकोण)

उदाहरण: एसिंक/प्रतीक्षा के साथ फ़ाइल प्रसंस्करण

// Using fs.promises (Node.js 10.0.0+)
const fs = require('fs').promises;

async function readFileExample() {
  try {
    const data = await fs.readFile('myfile.txt', 'utf8');
    console.log('File content:', data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}

readFileExample();

// Or with util.promisify (Node.js 8.0.0+)
const { promisify } = require('util');
const readFileAsync = promisify(require('fs').readFile);

async function readWithPromisify() {
  try {
    const data = await readFileAsync('myfile.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

readWithPromisify();

फ़ाइलों को अतुल्यकालिक रूप से ले जाना

उदाहरण: सिंक्रोनस फ़ाइल स्टेपिंग

const fs = require('fs');

try {
  // Read file synchronously
  const data = fs.readFileSync('myfile.txt', 'utf8');
  console.log('File content:', data);
} catch (err) {
  console.error('Error reading file:', err);
}

💡सर्वश्रेष्ठ प्रणालियां:

टेक्स्ट फ़ाइलें पास करते समय, एक कैरेक्टर एन्कोडिंग निर्दिष्ट करें (जैसे कि 'utf8'), जो बफ़र के बजाय एक स्ट्रिंग लौटाएगा।

फ़ाइलें बनाना और लिखना

Node.js .

यहां सबसे आम दृष्टिकोण हैं:

1. fs.writeFile() का उपयोग करना

उदाहरण: फाइल करने के लिए लिखना

const fs = require('fs').promises;

async function writeFileExample() {
  try {
    // Write text to a file
    await fs.writeFile('myfile.txt', 'Hello, World!', 'utf8');

    // Write JSON data
    const data = { name: 'John', age: 30, city: 'New York' };
    await fs.writeFile('data.json', JSON.stringify(data, null, 2), 'utf8');

    console.log('Files created successfully');
  } catch (err) {
    console.error('Error writing files:', err);
  }
}

writeFileExample();

2. fs.appendFile() का उपयोग करना

उदाहरण: फ़ाइल में जोड़ना

const fs = require('fs').promises;

async function appendToFile() {
  try {
    // Append a timestamped log entry
    const logEntry = `${new Date().toISOString()}: Application started\n`;
    await fs.appendFile('app.log', logEntry, 'utf8');

    console.log('Log entry added');
  } catch (err) {
    console.error('Error appending to file:', err);
  }
}

appendToFile();

3. फ़ाइल हैंडल का उपयोग करना

उदाहरण: फ़ाइल हैंडल का उपयोग करना

const fs = require('fs').promises;

async function writeWithFileHandle() {
  let fileHandle;

  try {
    // Open a file for writing (creates if doesn't exist)
    fileHandle = await fs.open('output.txt', 'w');

    // Write content to the file
    await fileHandle.write('First line\n');
    await fileHandle.write('Second line\n');
    await fileHandle.write('Third line\n');

    console.log('Content written successfully');
  } catch (err) {
    console.error('Error writing to file:', err);
  } finally {
    // Always close the file handle
    if (fileHandle) {
      await fileHandle.close();
    }
  }
}

writeWithFileHandle();

4. बड़ी फ़ाइलों के लिए स्ट्रीम का उपयोग करना

उदाहरण: स्ट्रीम के साथ बड़ी फ़ाइलें लिखना

const fs = require('fs');
const { pipeline } = require('stream/promises');
const { Readable } = require('stream');

async function writeLargeFile() {
  // Create a readable stream (could be from HTTP request, etc.)
  const data = Array(1000).fill().map((_, i) => `Line ${i + 1}: ${'x'.repeat(100)}\n`);
  const readable = Readable.from(data);

  // Create a writable stream to a file
  const writable = fs.createWriteStream('large-file.txt');

  try {
    // Pipe the data from readable to writable
    await pipeline(readable, writable);
    console.log('Large file written successfully');
  } catch (err) {
    console.error('Error writing file:', err);
  }
}

writeLargeFile();

फ़ाइल झंडे

झंडा व्याख्या
'w' लिखने के लिए खोलें (फ़ाइल बनाई गई या संपीड़ित की गई)
'wx' 'w' के समान लेकिन पथ मौजूद होने पर विफल हो जाता है
'w+' चरण के लिए खोलें और लिखें (फ़ाइल बनाई गई या संपीड़ित की गई)
'a' जोड़ने के लिए खोलें (यदि फ़ाइल नहीं बनी है)
'ax' 'ए' के ​​समान लेकिन पथ मौजूद होने पर विफल रहता है
'r+' चरण के लिए खोलें और लिखें (फ़ाइल होनी चाहिए)

फ़ाइलें और निर्देशिकाएँ हटाना

Node.js .

यहां विभिन्न विलोपन परिदृश्यों को संभालने का तरीका बताया गया है:

1. एकल फ़ाइल को हटाना

उदाहरण: किसी फ़ाइल को हटाना

const fs = require('fs').promises;

async function deleteFile() {
  const filePath = 'file-to-delete.txt';

  try {
    // Check if file exists before deleting
    await fs.access(filePath);

    // Delete the file
    await fs.unlink(filePath);
    console.log('File deleted successfully');
  } catch (err) {
    if (err.code === 'ENOENT') {
      console.log('File does not exist');
    } else {
      console.error('Error deleting file:', err);
    }
  }
}

deleteFile();

2. एकाधिक फ़ाइलें हटाना

उदाहरण: एकाधिक फ़ाइलें हटाना

const fs = require('fs').promises;
const path = require('path');

async function deleteFiles() {
  const filesToDelete = [
    'temp1.txt',
    'temp2.txt',
    'temp3.txt'
  ];

  try {
    // Delete all files in parallel
    await Promise.all(
      filesToDelete.map(file =>
        fs.unlink(file).catch(err => {
          if (err.code !== 'ENOENT') {
            console.error(`Error deleting ${file}:`, err);
          }
        })
      )
    );

    console.log('Files deleted successfully');
  } catch (err) {
    console.error('Error during file deletion:', err);
  }
}

deleteFiles();

3. निर्देशिकाएँ हटाना

उदाहरण: निर्देशिकाएँ हटाना

const fs = require('fs').promises;
const path = require('path');

async function deleteDirectory(dirPath) {
  try {
    // Check if the directory exists
    const stats = await fs.stat(dirPath);
   
    if (!stats.isDirectory()) {
      console.log('Path is not a directory');
      return;
    }

    // For Node.js 14.14.0+ (recommended)
    await fs.rm(dirPath, { recursive: true, force: true });

    // For older Node.js versions (deprecated but still works)
    // await fs.rmdir(dirPath, { recursive: true });

    console.log('Directory deleted successfully');
  } catch (err) {
    if (err.code === 'ENOENT') {
      console.log('Directory does not exist');
    } else {
      console.error('Error deleting directory:', err);
    }
  }
}

// Usage
deleteDirectory('directory-to-delete');

4. निर्देशिका को खाली करना (हटाए बिना)

उदाहरण: एक निर्देशिका खाली करना

const fs = require('fs').promises;
const path = require('path');

async function emptyDirectory(dirPath) {
  try {
    // Read the directory
    const files = await fs.readdir(dirPath, { withFileTypes: true });

    // Delete all files and directories in parallel
    await Promise.all(
      files.map(file => {
        const fullPath = path.join(dirPath, file.name);
        return file.isDirectory()
          ? fs.rm(fullPath, { recursive: true, force: true })
          : fs.unlink(fullPath);
      })
    );

    console.log('Directory emptied successfully');
  } catch (err) {
    console.error('Error emptying directory:', err);
  }
}

// Usage
emptyDirectory('directory-to-empty');

🔒सुरक्षा नोट:

फ़ाइल हटाने में बहुत सावधान रहें, विशेषकर पुनरावर्ती विकल्पों या वाइल्डकार्ड का उपयोग करते समय। डायरेक्टरी ट्रैवर्सल हमलों को रोकने के लिए हमेशा फ़ाइल पथों की जाँच करें और उन्हें साफ़ करें।

फ़ाइलों का नाम बदलना और स्थानांतरित करना

fs.rename() .

1. मूल फ़ाइल का नाम बदलना

उदाहरण: किसी फ़ाइल का नाम बदलना

const fs = require('fs').promises;

async function renameFile() {
  const oldPath = 'old-name.txt';
  const newPath = 'new-name.txt';

  try {
    // Check if source file exists
    await fs.access(oldPath);

    // Check if destination file already exists
    try {
      await fs.access(newPath);
      console.log('Destination file already exists');
      return;
    } catch (err) {
      // Destination doesn't exist, safe to proceed
    }

    // Perform the rename
    await fs.rename(oldPath, newPath);
    console.log('File renamed successfully');
  } catch (err) {
    if (err.code === 'ENOENT') {
      console.log('Source file does not exist');
    } else {
      console.error('Error renaming file:', err);
    }
  }
}

// Usage
renameFile();

2. निर्देशिकाओं के बीच फ़ाइलें ले जाना

उदाहरण: किसी फ़ाइल को किसी भिन्न निर्देशिका में ले जाना

const fs = require('fs').promises;
const path = require('path');

async function moveFile() {
  const sourceFile = 'source/file.txt';
  const targetDir = 'destination';
  const targetFile = path.join(targetDir, 'file.txt');

  try {
    // Ensure source file exists
    await fs.access(sourceFile);

    // Create target directory if it doesn't exist
    await fs.mkdir(targetDir, { recursive: true });

    // Move the file
    await fs.rename(sourceFile, targetFile);

    console.log('File moved successfully');
  } catch (err) {
    if (err.code === 'ENOENT') {
      console.log('Source file does not exist');
    } else if (err.code === 'EXDEV') {
      console.log('Cross-device move detected, using copy+delete fallback');
      await moveAcrossDevices(sourceFile, targetFile);
    } else {
      console.error('Error moving file:', err);
    }
  }
}

// Helper function for cross-device moves
async function moveAcrossDevices(source, target) {
  try {
    // Copy the file
    await fs.copyFile(source, target);

    // Delete the original
    await fs.unlink(source);

    console.log('File moved across devices successfully');
  } catch (err) {
    // Clean up if something went wrong
    try { await fs.unlink(target); } catch (e) {}
    throw err;
  }
}

// Usage
moveFile();

3. बैच नाम बदलने वाली फ़ाइलें

उदाहरण: बैच नाम बदलने वाली फ़ाइलें

const fs = require('fs').promises;
const path = require('path');

async function batchRename() {
  const directory = 'images';
  const pattern = /^image(\d+)\.jpg$/;

  try {
    // Read directory contents
    const files = await fs.readdir(directory);

    // Process each file
    for (const file of files) {
      const match = file.match(pattern);
      if (match) {
        const [_, number] = match;
        const newName = `photo-${number.padStart(3, '0')}.jpg`;
        const oldPath = path.join(directory, file);
        const newPath = path.join(directory, newName);

        // Skip if the new name is the same as the old name
        if (oldPath !== newPath) {
          await fs.rename(oldPath, newPath);
          console.log(`Renamed: ${file} - ${newName}`);
        }
      }
    }

    console.log('Batch rename completed');
  } catch (err) {
    console.error('Error during batch rename:', err);
  }
}

batchRename();

4. परमाणु नामकरण संक्रियाएँ

उदाहरण: परमाणु फ़ाइल अद्यतन

const fs = require('fs').promises;
const path = require('path');
const os = require('os');

async function updateFileAtomic(filePath, newContent) {
  const tempPath = path.join(
    os.tmpdir(),
    `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
  );

  try {
    // 1. Write to temp file
    await fs.writeFile(tempPath, newContent, 'utf8');

    // 2. Verify the temp file was written correctly
    const stats = await fs.stat(tempPath);
    if (stats.size === 0) {
      throw new Error('Temporary file is empty');
    }

    // 3. Rename (atomic on most systems)
    await fs.rename(tempPath, filePath);

    console.log('File updated atomically');
  } catch (err) {
    // Clean up temp file if it exists
    try { await fs.unlink(tempPath); } catch (e) {}

    console.error('Atomic update failed:', err);
    throw err;
  }
}

// Usage
updateFileAtomic('important-config.json', JSON.stringify({ key: 'value' }, null, 2));

💻क्रॉस-प्लेटफ़ॉर्म नोट:

fs.rename() .

क्रॉस-प्लेटफ़ॉर्म परमाणु संचालन के लिए, ऊपर दिए गए उदाहरण में दिखाए गए अस्थायी फ़ाइल एक्सेस विधि का उपयोग करें।

अभ्यास

वाक्य को पूरा करने के लिए सही शब्द को खींचें और छोड़ें।

Node.js provides both ______ and asynchronous methods for file operations.

synchronous
✓ ठीक है! Node.js फ़ाइल संचालन के लिए सिंक्रोनस और एसिंक्रोनस दोनों तरीके प्रदान करता है।
parallel
✗ ग़लत! "समानांतर" सही शब्द नहीं है. Node.js सिंक्रोनस और एसिंक्रोनस तरीके प्रदान करता है।
sequential
✗ ग़लत! "अनुक्रमिक" सही शब्द नहीं है. Node.js सिंक्रोनस और एसिंक्रोनस तरीके प्रदान करता है।
linear
✗ ग़लत! "रैखिक" सही शब्द नहीं है. Node.js सिंक्रोनस और एसिंक्रोनस तरीके प्रदान करता है।